package com.sky.Task;

import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 处理超时订单(每分钟检查)
     */
    @Transactional
    @Scheduled(cron = "0 * * * * ?")
    public void handleTimeoutOrder() {
        log.info("处理超时订单:{}",LocalDateTime.now());
        //获取超时的订单
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = ordersMapper.getOrderStatus(Orders.PENDING_PAYMENT,orderTime);

        if (CollectionUtils.isEmpty(ordersList)) {
            return;
        }
        //修改订单状态为已取消
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("超时未支付");
            ordersMapper.update(orders);
        });
    }

    /**
     * 每天打烊后修改派送中的订单为已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void completeOrder() {
        log.info("修改派送中的订单为已完成:{}",LocalDateTime.now());
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(60);
        List<Orders> orderList = ordersMapper.getOrderStatus(Orders.DELIVERY_IN_PROGRESS, orderTime);
        if (CollectionUtils.isEmpty(orderList)) {
            return;
        }
        orderList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            ordersMapper.update(orders);
        });
    }
}
